//
//  SEGLoginViewController.m
//  Login
//
//  Created by 梁昆 on 16/8/15.
//  Copyright © 2016年 segiK. All rights reserved.
//

#import "SEGLoginViewController.h"
#import "SEGForgetPasswordViewController.h"
#import "SEGRegisterViewController.h"
#import <SafariServices/SafariServices.h>
#import <Commom/SEGSecurityManager.h>
#import <SEGPlatform/SEGSecurityConfirmView.h>
#import "SEGAuthCodeView.h"
#import "SEGLoginViewModel.h"

@interface SEGLoginViewController () <LoginProtocol, UIScrollViewDelegate>

@property (nonatomic, strong) UIView *selectedView;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) SEGLoginRightView *LoginView;
@property (nonatomic, assign) BOOL isGotoPrivacy;
@property (nonatomic, strong) SEGAuthCodeView *codeView;
@property (nonatomic, strong) SEGSecurityConfirmView *securityConfirmView;

/// viewModel
@property (nonatomic, strong) SEGLoginViewModel *viewModel;

@end

@implementation SEGLoginViewController {
    BOOL isRequest;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    NSString *message = @"";
    // 兼容老逻辑
    if ([self.messageDesc objectForKey:@"ResultDesc"] && [[self.messageDesc valueForKey:@"ResultDesc"] length] > 0) {
        message = [self.messageDesc valueForKey:@"ResultDesc"];
    }
    if ([self.messageDesc objectForKey:@"message"] && [[self.messageDesc valueForKey:@"message"] length] > 0) {
        message = [self.messageDesc valueForKey:@"message"];
    }
    if ([message length] > 0) {
        [SEGAlertView showTmepMessageWithMessage:message];
    }
    self.messageDesc = nil;// 清空，防止每次进来都提示
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
//    NSString *strTel = [SEGLoginV2Manager segUserTelFromLocal];
//    NSString *strNpwd = [SEGLoginV2Manager segUserPasswordFromLocal];
//    // 修改手机号后，清空手机号和密码（防止以后其他地方传手机号和密码，目前传空字符）
//    if ([self.messageDesc objectForKey:@"phone"]) {
//        strTel = [self.messageDesc valueForKey:@"phone"];
//    }
//    if ([self.messageDesc objectForKey:@"password"]) {
//        strNpwd = [self.messageDesc valueForKey:@"password"];
//    }
//    [self.LoginView setPhoneText:strTel passwordText:strNpwd];
    
    // 展示登录界面 表示未登录
    [SEGLoginV2Manager seg_saveSignOutStatus:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // 每次进入登录页面都先清除本地cookie
    [[SEGHTTPManager sharedNetworkManager] removeCookies];
    self.navDisplayType = SEGNavigationBarDisplayTypeHide;
    self.view.backgroundColor = kColor_W;
    
    [self.view addSubview:self.LoginView];
    self.LoginView.frame = CGRectMake(0, 0, LYScreenWidth(), LYScreenWidth());
    [self.LoginView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    // 每次进入登录页面都先清除本地cookie
    [[SEGHTTPManager sharedNetworkManager] removeCookies];
    
    // 界面赋值默认数据
    [self updateUIWithDefaultValue];
    
    // 判断是否同意安全隐私政策
    if (![SEGSecurityManager isAgreeSecurity]) {
        WeakSelf;
        SEGSecurityConfirmView *confirmView = [[SEGSecurityConfirmView alloc] init];
        confirmView.agreeBlock = ^{
            [SEGSecurityManager updateLocalSecurityVersion];
        };
        confirmView.disagreeBlock = ^{
            [SEGAlertView showTmepMessageWithMessage:@"如不同意用户协议和隐私政策，\n无法登录使用" withtime:1];
        };
        confirmView.checkSecurityBlock = ^{
            [weakSelf gotoPrivacy];
        };
        confirmView.checkUserAgreementBlock = ^{
            [weakSelf gotoUserAgreement];
        };
        self.securityConfirmView = confirmView;
        self.securityConfirmView.frame = [UIScreen mainScreen].bounds;
        [self.view addSubview:self.securityConfirmView];
    }
    // 键盘通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShowChangeFrame:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHideChangeFrame:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    // 注册通知 监听用户截屏
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleUserDidTakeScreenshot:)
                                                 name:UIApplicationUserDidTakeScreenshotNotification object:nil];
    
    if (@available(iOS 11.0, *)) {
        // 监测当前设备是否处于录屏状态
        if ([UIScreen mainScreen].isCaptured) {
            [SEGAlertView showTmepMessageWithMessage:KDetectScreenCapturedTipMessage withtime:2];
        }
        // 监听用户是否录屏
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleScreenCapturedDidChange:)
                                                     name:UIScreenCapturedDidChangeNotification
                                                   object:nil];
    }
    
    // 忘记密码成功的通知 刷新UI
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleForgetPasswordSuccessNotification:) name:kForgerPasswordSuccessNotification object:nil];
}

- (void)updateUIWithDefaultValue {
    NSString *strTel = [SEGLoginV2Manager segUserTelFromLocal];
    NSString *strNpwd = [SEGLoginV2Manager segUserPasswordFromLocal];
    [self.LoginView setPhoneText:strTel passwordText:strNpwd];
}

#pragma mark - NSNotification
- (void)handleUserDidTakeScreenshot:(NSNotification *)notification {
    [SEGAlertView showTmepMessageWithMessage:KDetectScreenShotTipMessage withtime:2];
}

- (void)handleScreenCapturedDidChange:(NSNotification *)notification {
    NSLog(@"%s %@", __func__, notification);
    if (@available(iOS 11.0, *)) {
        if ([UIScreen mainScreen].isCaptured) {
            [SEGAlertView showTmepMessageWithMessage:KDetectScreenCapturedTipMessage withtime:2];
        }
    }
}

// 收到修改密码成功通知：更新UI
- (void)handleForgetPasswordSuccessNotification:(NSNotification *)notification {
    [self updateUIWithDefaultValue];
}

- (void)keyboardWillShowChangeFrame:(NSNotification *)notification {
    NSDictionary *info = [notification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    if (CGRectGetMinY(self.view.frame) < 0) {
        return;
    }
    // 保证最下面的控件不被遮挡
    CGFloat bottomY = LYScreenHeight();
    if ([UIScreen mainScreen].bounds.size.height == 480 || [UIScreen mainScreen].bounds.size.height ==  568.0f) {
        bottomY = CGRectGetMaxY(self.LoginView.gotoRegister.frame) + CGRectGetMinY(self.view.frame);
    }
    NSTimeInterval duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        if ([UIScreen mainScreen].bounds.size.height == 480 || [UIScreen mainScreen].bounds.size.height ==  568.0f) {
            self.view.frame = CGRectMake(0, -kbSize.height + (LYScreenHeight() - bottomY), CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds));
        } else {
            self.view.frame = CGRectMake(0, 0, LYScreenWidth(), LYScreenHeight());
        }
    }];
}

- (void)keyboardWillHideChangeFrame:(NSNotification *)notification {
    NSDictionary *info = [notification userInfo];
    NSTimeInterval duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        self.view.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds));
    }];
}

#pragma mark - RegiserDelegate
// 提示用户去注册   代理方法
-(void)GotoRegister {
    SEGRegisterViewController *vc = [[SEGRegisterViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
// 忘记密码跳转另一个controller
- (void)losePasswordWithPhoneNumber:(NSString *)phoneNumber {
    SEGForgetPasswordViewController* viewControllerFP = [[SEGForgetPasswordViewController alloc] init];
    viewControllerFP.phoneNumber = phoneNumber;
    [self.navigationController pushViewController:viewControllerFP animated:YES];
}
// 获取进入app 网络请求
- (void)enterLogin:(NSDictionary *)params {
    [self requestLoginWithImgCode:nil randomToken:nil];
}
- (void)requestLoginWithImgCode:(NSString *)imgCode randomToken:(NSString *)randomToken {
    NSString *tel = self.LoginView.phoneText.text ?: @"";
    NSString *password = self.LoginView.passwordText.text ?: @"";
    RACTuple *tuple = RACTuplePack(tel, password, imgCode, randomToken);
    [self.viewModel.loginCommand.executing subscribeNext:^(NSNumber * _Nullable x) {
        if (x.boolValue) {
            [SVProgressHUD show];
        } else {
            [SVProgressHUD dismiss];
        }
    }];
    @weakify(self);
    [[self.viewModel.loginCommand execute:tuple] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        NSDictionary *params = @{@"ShowLoading":@(YES), @"isAlreadyLogin": @(YES)};
        [self.codeView dismiss];
        [[SEGUhomeMediator sharedInstance] seg_pushToMainViewControllerThroughInterface:params];
    } error:^(NSError * _Nullable error) {
        // 20010：用户名密码错误5次，且当前还没有验证码弹窗的时候，需要则立即弹出弹窗
        if (!self.codeView.isShow && error.code == 20010) {
            [self showAuthCodeView];
            return;
        }
        // 20020：图形验证码错误, 刷新图形验证码
        if (error.code == 20020) {
            [self showAuthCodeView];
            [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
            return;
        }
        
        // 其他情况都关闭codeView，并提示
        [self.codeView dismiss];
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
    }];
}
- (void)showAuthCodeView {
    WeakSelf;
    self.codeView.confirmBlock = ^(NSString *code, NSString *randomToken) {
        [weakSelf requestLoginWithImgCode:code randomToken:randomToken];
    };
    [self.codeView show];
}
- (void)gotoPrivacy {
    NSString *urlStr = [NSString stringWithFormat:@"%@%@?app_platform_code=%@&company_platform_code=%@",kClientRootURL,@"/h5/policy/policy.html",kAppPlatformCode,kAppPlatformCode];
    NSDictionary *params = @{@"linkURL":urlStr};
    UIViewController *vc = [[SEGUhomeMediator sharedInstance] seg_initWebViewLoadController:params];
    vc.title = [NSString stringWithFormat:@"%@隐私政策", kAppName];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)gotoUserAgreement {
    NSString *urlStr = kUhomeUseRegulation;
    NSDictionary *params = @{@"linkURL":urlStr};
    UIViewController *vc = [[SEGUhomeMediator sharedInstance] seg_initWebViewLoadController:params];
    vc.title = [NSString stringWithFormat:@"%@使用服务条例", kAppName];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - Event
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

#pragma mark - Getter
- (SEGLoginRightView *)LoginView {
    if (!_LoginView) {
        _LoginView = [[SEGLoginRightView alloc] init];
        _LoginView.loginDelegate = self;
    }
    return _LoginView;
}
- (SEGAuthCodeView *)codeView {
    if (!_codeView) {
        _codeView = [SEGAuthCodeView new];
        _codeView.hidden = YES;
        _codeView.style = SEGAuthCodeViewSecurityStyle;
        [[UIApplication sharedApplication].delegate.window addSubview:_codeView];
    }
    return _codeView;
}
- (SEGLoginViewModel *)viewModel {
    if (!_viewModel) _viewModel = [SEGLoginViewModel new];
    return _viewModel;
}

@end
